from flask_restx import Namespace, Resource, reqparse, fields
from flask import request
from .modles import Account, set_position_mode
from app.common.response import api_response

multi_account_ns = Namespace('multi_account', description='账户管理API')


@multi_account_ns.route('/accounts')
class AccountList(Resource):
    def get(self):
        """
        返回数据库中所有账户信息
        """
        try:
            accounts = Account.query.all()  # Directly using the model query to get all accounts
            accounts_data = [
                {'id': account.id, 'name': account.name, 'gate_key': account.gate_key,
                 'gate_secret': account.gate_secret, 'contingent': account.contingent}
                for account in accounts
            ]
            return api_response(200, accounts_data, "查询成功")
        except Exception as e:
            # 如果获取账户信息出现错误，返回错误状态和消息
            return api_response(500, message=str(e))


@multi_account_ns.route('/accounts/<int:id>')
class AccountDetail(Resource):
    def get(self, id):
        """
        根据ID返回单个账户的详细信息
        """
        try:
            account = Account.query.get(id)
            if account is None:
                return api_response(404, message="账户不存在")
            account_data = {
                'id': account.id,
                'name': account.name,
                'gate_key': account.gate_key,
                'gate_secret': account.gate_secret,
                'contingent': account.contingent
            }
            return api_response(200, account_data, "查询成功")
        except Exception as e:
            # 处理数据库查询错误或其他意外错误
            return api_response(500, message=str(e))


@multi_account_ns.route('/login/<string:name>/<string:password>')
class AccountLogin(Resource):
    def get(self, name, password):
        """
        账号登录
        """
        try:
            account = Account.query.filter_by(name=name, password=password).first()
            if account is None:
                return api_response(404, message="账户不存在")
            if account.password != password:
                return api_response(401, message="密码错误")
            account_data = {
                'id': account.id,
                'name': account.name,
                'gate_key': account.gate_key,
                'gate_secret': account.gate_secret
            }
            return api_response(200, account_data, "登录成功")
        except Exception as e:
            # 处理数据库查询错误或其他意外错误
            return api_response(500, message=str(e))


parser = reqparse.RequestParser()
parser.add_argument('contingent', type=str, required=True, help="需要查询的Contingent值")


@multi_account_ns.route('/accounts/search')
class AccountSearch(Resource):
    @multi_account_ns.expect(parser)
    def get(self):
        """
        根据Contingent字段返回匹配的账户信息
        """
        args = parser.parse_args()  # 解析请求中的参数
        contingent_value = args['contingent']  # 获取contingent参数的值

        try:
            # 查询含有特定contingent值的账户
            accounts = Account.query.filter_by(contingent=contingent_value).all()
            if not accounts:
                return api_response(404, message="没有找到匹配的账户")

            accounts_data = [
                {'id': account.id, 'name': account.name, 'gate_key': account.gate_key,
                 'gate_secret': account.gate_secret, 'contingent': account.contingent}
                for account in accounts
            ]
            return api_response(200, accounts_data, "查询成功")
        except Exception as e:
            return api_response(500, message=str(e))


account_model = multi_account_ns.model('Account', {
    'name': fields.String(required=True, description='账户名称'),
    'gate_key': fields.String(required=True, description='Gate.io API Key'),
    'gate_secret': fields.String(required=True, description='Gate.io API Secret'),
    'contingent': fields.String(required=True, description='特定条件字段')
})


@multi_account_ns.route('/accounts/add')
class AccountList(Resource):
    @multi_account_ns.expect(account_model, validate=True)
    def post(self):
        """
        创建新账户
        """
        data = multi_account_ns.payload  # 使用 namespace.payload 获取请求数据
        try:
            new_account = Account.create_account(
                name=data['name'],
                gate_key=data['gate_key'],
                gate_secret=data['gate_secret'],
                contingent=data['contingent']
            )
            return api_response(200, {
                'id': new_account.id,
                'name': new_account.name,
                'gate_key': new_account.gate_key,
                'gate_secret': new_account.gate_secret,
                'contingent': new_account.contingent
            }, "账户创建成功")
        except Exception as e:
            return api_response(500, message=str(e))


@multi_account_ns.route('/accounts/del/<int:id>')
class AccountDetail(Resource):
    def delete(self, id):
        """
        根据ID删除账户
        """
        account = Account.query.get(id)
        if not account:
            return api_response(404, message="账户不存在")

        try:
            account.delete()
            return api_response(200, message="账户删除成功")
        except Exception as e:
            return api_response(500, message=str(e))


@multi_account_ns.route('/accounts/updata/<int:id>')
class AccountDetail(Resource):
    @multi_account_ns.expect(account_model, validate=True)
    def put(self, id):
        """
        根据ID更新账户信息
        """
        account = Account.query.get(id)
        if not account:
            return api_response(404, message="账户不存在")

        data = multi_account_ns.payload
        try:
            account.update(
                name=data.get('name'),
                gate_key=data.get('gate_key'),
                gate_secret=data.get('gate_secret'),
                contingent=data.get('contingent')
            )
            return api_response(200, {
                'id': account.id,
                'name': account.name,
                'gate_key': account.gate_key,
                'gate_secret': account.gate_secret,
                'contingent': account.contingent
            }, "账户更新成功")
        except Exception as e:
            return api_response(500, message=str(e))



position_mode_model = multi_account_ns.model('PositionMode', {
    'gate_key': fields.String(required=True, description='Gate.io API Key'),
    'gate_secret': fields.String(required=True, description='Gate.io API Secret'),
    'settle': fields.String(required=True, description='结算货币'),
    'dual_mode': fields.Boolean(required=True, description='是否启用双仓模式')
})

@multi_account_ns.route('/control_position_mode')
class ControlPositionMode(Resource):
    @multi_account_ns.expect(position_mode_model, validate=True)
    def post(self):
        """
        设置账户的仓位模式
        """
        data = request.json
        gate_key = data['gate_key']
        gate_secret = data['gate_secret']
        settle = data['settle']
        dual_mode = data['dual_mode']

        # 调用模型中的函数处理业务逻辑
        result = set_position_mode(gate_key, gate_secret, settle, dual_mode)
        return result, result.get("code", 200)

